<?php
namespace app\index\controller\store;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据
use szktor\MyExcel;

/*
* 前台-库房管理 -> 库存管理
* index/store.kucun/index
*/
class Kucun extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = []; //无需鉴权的方法，但需要登录

    //初始化
    public function initialize()
    {
        parent::initialize();
    }

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            //首页 和导出 共用方法
            $res = $this->afterSql();
            return json($res);
        }
        $this->assign([
            'ypkc_type_list' => ClinicDict::getKuCunXmTypeList(), //库存药品项目类型
        ]);
        return $this->view->fetch();
    }
    //库存index方法中的列表 导出Excel index/store.kucun/to_excel
    public function to_excel()
    {
        //首页 和导出 共用方法
        $res = $this->afterSql(true);
        $list = [];
        if(isset($res['code']) && $res['code'] == 0)
        {
            $list = $res['data'];
        }
        try
        {
            $csvList = [];
            foreach ($list as $key => &$val) {
              $csvList[] = [
                  $key+1,
                  $val['xm_type_txt'],
                  $val['name'],
                  $val['spec'],
                  $val['huogui_no'],
                  $val['changjia'],
                  $val['cost_price'],
                  $val['price'],
                  $val['ls_unit'],
                  $val['stock'],
              ];
            }
            $headArr = ['序号','药品类型','名称','规格','货柜号','生产厂家','进货价','零售价','单位','库存总量']; //字段
            MyExcel::exportToExcel($headArr,$csvList,$this->clinic['short_name'] . '_库存明细记录','库存明细记录');
            die();
        }catch (\think\Exception $e){ // use think\Exception;
            return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //首页 和导出 共用方法
    private function afterSql($saveExcel = false)
    {
        try
        {
            $data = $this->request->only(['drugtype','keyword','zeronoshow','page'],'post');
            if(!$saveExcel && !isset($data['page']))
            {
                return ['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []];
            }
            //条件
            $map = [['clinic_id','=', $this->admin['clinic_id']]];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|jd_name|bianma|py_code|wb_code|changjia','like','%' . $data['keyword'] . '%'];
            }
            if(isset($data['drugtype']) && $data['drugtype'] != '')
            {
                //xy=西药,zcy=中成药,zyyp=中药饮片,zykl=中药颗粒,cl=材料
                if(strtoupper($data['drugtype']) != 'ALL')
                {
                    if($data['drugtype'] == 'xy') //西药
                    {
                        $map[] = ['drugs_type','=','0'];
                        $map[] = ['yp_type','=','0'];
                    }
                    if($data['drugtype'] == 'zcy') //中成药
                    {
                        $map[] = ['drugs_type','=','0'];
                        $map[] = ['yp_type','=','1'];
                    }
                    if($data['drugtype'] == 'zyyp') //中药饮片
                    {
                        $map[] = ['drugs_type','=','1'];
                        $map[] = ['yp_type','=','0'];
                    }
                    if($data['drugtype'] == 'zykl') //中药颗粒
                    {
                        $map[] = ['drugs_type','=','1'];
                        $map[] = ['yp_type','=','0'];
                    }
                    if($data['drugtype'] == 'cl') //材料
                    {
                        $map[] = ['drugs_type','=','2'];
                    }
                }      
            }
            if(isset($data['zeronoshow']) && (int)$data['zeronoshow'] > 0)
            {
                $map[] = ['stock','>','0'];
            }
            $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
            $field = '*';
            //导出为Excel
            if($saveExcel)
            {
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field($field)
                    ->order('id desc')->select();
            }else{
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field($field)
                    ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            }
            if (count($list) <= 0) {
                return ['code' => '3', 'msg' => '当前页下无数据', 'count' => '0', 'data' => []];
            }
            //库存药品项目类型
            $ypkc_type_list = ClinicDict::getKuCunXmTypeList();
            $xy_zjunit_list = ClinicDict::getDrugsZhiJiUnitList(); //西药 - 制剂单位
            $xy_kcunit_list = ClinicDict::getDrugsKuCunUnitList(); //西药 - 库存单位
            $zy_kcunit_list = ClinicDict::getZhongYaoUnitList(); //中药(销售单位+库存单位)、材料(最小单位+库存单位)
            $res = ['code' => 0,
                'cost_total' => 0,  //进货总额
                'sale_total' => 0, //零售总额
                'msg' => '',
                'count' => !$saveExcel ? $list->total() : count($list),
                'data' => !$saveExcel ? $list->items() : $list,
            ];
            foreach ($res['data'] as $key => &$val) {
                //类型,0=西药,1=中药,2=材料
                if($val['drugs_type'] == 0) //西药
                {
                    $val['ls_unit'] = _getDictNameTxt($val['kc_unit'],$xy_kcunit_list);
                    if((int)$val['is_cl'] > 0)
                    {
                        $val['price'] = $val['cl_price'];
                        $val['ls_unit'] = _getDictNameTxt($val['zj_unit'],$xy_zjunit_list);
                    }
                    $val['spec'] = _getXiYaoSpecText($val);
                }
                //中药
                if($val['drugs_type'] == 1)
                {
                    $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$xy_zjunit_list);
                }
                //材料
                if($val['drugs_type'] == 2)
                {
                    $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$zy_kcunit_list);
                }
                //库存药品项目类型
                $val['xm_type_txt'] = _getDictNameTxt($this->getXmType($val),$ypkc_type_list);
                //进货总额
                $res['cost_total'] += $val['cost_price']*$val['stock'];
                //零售总额
                $res['sale_total'] += $val['price']*$val['stock'];
            }
            return $res;
        }catch (\think\Exception $e){ // use think\Exception;
            return ['code' => '500', 'msg' => '错误：' . $e->getMessage(), 'count' => '0', 'data' => []];
        }
    }
    //库存设置 index/store.kucun/kucun_set
    public function kucun_set()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
            //修改字段值
                $action = $this->request->post('action');
                if($action && strtolower($action) == 'edit')
                {
                    $post = $this->request->only(['id','field','value'],'post');
                    try
                    {
                        if(!isset($post['id']) || intval($post['id']) <= 0)
                        {
                            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
                        }
                        if(!isset($post['field']) || empty($post['field']))
                        {
                            return json(['err' => '2', 'msg' => '参数错误，无法执行']);
                        }
                        if(!isset($post['value']))
                        {
                            return json(['err' => '3', 'msg' => '参数错误，无法执行']);
                        }
                        //条件
                        $map = [['id','=',$post['id']],['clinic_id','=', $this->admin['clinic_id']]];
                        $res = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)
                                ->update([$post['field'] => $post['value']]);
                        if(!$res) return json(['err' => '2', 'msg' => '数据更新失败，请重试']);
                        return json(['err' => '0', 'msg' => '数据更新成功']);
                    }catch (\think\Exception $e){ // use think\Exception;
                        return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
                    }
                }
            //获取列表数据
                $data = $this->request->only(['drugtype','keyword','hghnoset','zeronoshow','page'],'post');
                if(!isset($data['page']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                //条件
                $map = [['clinic_id','=', $this->admin['clinic_id']]];
                if(isset($data['keyword']) && $data['keyword'] != '')
                {
                    $map[] = ['name|jd_name|bianma|py_code|wb_code|changjia','like','%' . $data['keyword'] . '%'];
                }
                if(isset($data['drugtype']) && $data['drugtype'] != '')
                {
                    //xy=西药,zcy=中成药,zyyp=中药饮片,zykl=中药颗粒,cl=材料
                    if(strtoupper($data['drugtype']) != 'ALL')
                    {
                        if($data['drugtype'] == 'xy') //西药
                        {
                            $map[] = ['drugs_type','=','0'];
                            $map[] = ['yp_type','=','0'];
                        }
                        if($data['drugtype'] == 'zcy') //中成药
                        {
                            $map[] = ['drugs_type','=','0'];
                            $map[] = ['yp_type','=','1'];
                        }
                        if($data['drugtype'] == 'zyyp') //中药饮片
                        {
                            $map[] = ['drugs_type','=','1'];
                            $map[] = ['yp_type','=','0'];
                        }
                        if($data['drugtype'] == 'zykl') //中药颗粒
                        {
                            $map[] = ['drugs_type','=','1'];
                            $map[] = ['yp_type','=','0'];
                        }
                        if($data['drugtype'] == 'cl') //材料
                        {
                            $map[] = ['drugs_type','=','2'];
                        }
                    }      
                }
                if(isset($data['zeronoshow']) && (int)$data['zeronoshow'] > 0)
                {
                    $map[] = ['stock','>','0'];
                }
                if(isset($data['hghnoset']) && (int)$data['hghnoset'] > 0)
                {
                    $map[] = ['huogui_no','=',''];
                }
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $field = '*';
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field($field)
                        ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '3', 'msg' => '当前页下无数据', 'count' => '0', 'data' => []]);
                }
                //库存药品项目类型
                $ypkc_type_list = ClinicDict::getKuCunXmTypeList();
                $xy_zjunit_list = ClinicDict::getDrugsZhiJiUnitList(); //西药 - 制剂单位
                $xy_kcunit_list = ClinicDict::getDrugsKuCunUnitList(); //西药 - 库存单位
                $zy_kcunit_list = ClinicDict::getZhongYaoUnitList(); //中药(销售单位+库存单位)、材料(最小单位+库存单位)
                $res = ['code' => 0, 'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                foreach ($res['data'] as $key => &$val) {
                    //类型,0=西药,1=中药,2=材料
                    if($val['drugs_type'] == 0) //西药
                    {
                        $val['ls_unit'] = _getDictNameTxt($val['kc_unit'],$xy_kcunit_list);
                        if((int)$val['is_cl'] > 0)
                        {
                            $val['price'] = $val['cl_price'];
                            $val['ls_unit'] = _getDictNameTxt($val['zj_unit'],$xy_zjunit_list);
                        }
                        $val['spec'] = _getXiYaoSpecText($val);
                    }
                    //中药
                    if($val['drugs_type'] == 1)
                    {
                        $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$xy_zjunit_list);
                    }
                    //材料
                    if($val['drugs_type'] == 2)
                    {
                        $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$zy_kcunit_list);
                    }
                    //库存药品项目类型
                    $val['xm_type_txt'] = _getDictNameTxt($this->getXmType($val),$ypkc_type_list);
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['code' => '500', 'msg' => '错误：' . $e->getMessage(), 'count' => '0', 'data' => []]);
            }
        }
        $this->assign([
            'ypkc_type_list' => ClinicDict::getKuCunXmTypeList(), //库存药品项目类型
        ]);
        return $this->view->fetch();
    }
    //有效期查询 index/store.kucun/except_query
    public function except_query()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $post = $this->request->only(['create_time','zeronoshow','xm_type','keyword','except_num','page'],'post');
                //条件
                $map = [
                    ['clinic_id','=', $this->admin['clinic_id']],
                    ['entry_type','=','0'], //出入类型0=入库,1=出库
                    ['status','=','1'], //已确认
                ];
                if(isset($post['xm_type']) && $post['xm_type'] != '')
                {
                    if(strtoupper($post['xm_type']) != 'ALL') $map[] = ['xm_type','=',$post['xm_type']];
                }
                if(isset($post['keyword']) && $post['keyword'] != '')
                {
                    $map[] = ['batch_sn|name|py_code|wb_code|changjia|chandi','like','%' . $post['keyword'] . '%'];
                }
                if(isset($data['zeronoshow']) && (int)$data['zeronoshow'] > 0)
                {
                    $map[] = ['num','>','0'];
                }
                //日期
                $rkDate = $this->getWhereDate($post['create_time']);
                if($rkDate) $map[] = ['create_time',['>=',$rkDate[0]],['<=',$rkDate[1]],'AND'];
                
                //过期条件 -- 0=已过期,30=30天内过期,90=90天内过期,183=6个月内过期,365=一年内过期
                $exceptNum = isset($post['except_num']) ? intval($post['except_num']) : 0;
                if($exceptNum !== '')
                {
                    $map[] = ['except_time','<=',strtotime('+'.$exceptNum.' days')];
                }
                //分页
                $page = isset($post['page']) ? $post['page'] : 1;
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_entry_log')->where($map)->field('*')
                        ->order('id desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
                }
                $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                //仓库管理 - 库存药品项目类型
                $ypkc_type_list = ClinicDict::getKuCunXmTypeList();
                foreach ($res['data'] as $key => &$val) {
                    unset($val['ext_json']);
                    $val['xm_type_txt'] = _getDictNameTxt($val['xm_type'],$ypkc_type_list);
                    $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d',$val['create_time']) : '';
                    $val['except_time'] = $val['except_time'] > 0 ? date('Y-m-d',$val['except_time']) : '';
                    $val['product_time'] = $val['product_time'] > 0 ? date('Y-m-d',$val['product_time']) : '';
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
        $this->assign([
            'rk_type_list' => ClinicDict::getRuKuTypeList(), //仓库管理 - 入库类型
        ]);
        return $this->view->fetch();
    }
    //批次查询 index/store.kucun/batch_query
    public function batch_query($drugs_id = 0, $drugs_name = '')
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $post = $this->request->only(['drugs_id','page'],'post');
                //条件
                $map = [
                    ['clinic_id','=', $this->admin['clinic_id']],
                    ['entry_type','=','0'], //出入类型0=入库,1=出库
                    ['status','=','1'], //已确认
                    ['drugs_id','=',(int)$post['drugs_id']], //已确认
                ];
                //分页
                $page = isset($post['page']) ? $post['page'] : 1;
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_entry_log')->where($map)->field('*')
                        ->order('id desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
                }
                $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                foreach ($res['data'] as $key => &$val) {
                    unset($val['ext_json']);
                    $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d',$val['create_time']) : '';
                    $val['except_time'] = $val['except_time'] > 0 ? date('Y-m-d',$val['except_time']) : '';
                    $val['product_time'] = $val['product_time'] > 0 ? date('Y-m-d',$val['product_time']) : '';
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
        $this->assign([
            'drugs_id' => $drugs_id,
            'drugs_name' => $drugs_name,
        ]);
        return $this->view->fetch();
    }

    //进销存明细 index/store.kucun/inout_query
    public function inout_query($drugs_id = 0, $drugs_name = '')
    {
        //出入库方式
        $crkType = ClinicDict::getChuRuKuTypeList();
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $data = $this->request->only(['drugs_id','create_time','type','keyword','page'],'post');
                if(!isset($data['page']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                //条件
                $map = [['clinic_id','=', $this->admin['clinic_id']]];
                if(isset($data['drugs_id']) && intval($data['drugs_id']) > 0)
                {
                    $map[] = ['drugs_id','=',$data['drugs_id']];
                }
                if(isset($data['keyword']) && $data['keyword'] != '')
                {
                    $map[] = ['inout_sn|name|py_code|wb_code|batch_sn|changjia','like','%' . $data['keyword'] . '%'];
                }
                //日期
                $rkDate = $this->getWhereDate($data['create_time']);
                if($rkDate) $map[] = ['create_time',['>=',$rkDate[0]],['<=',$rkDate[1]],'AND'];
                //出入库方式
                if(isset($data['type']) && $data['type'] != '')
                {
                    if(strtoupper($data['type']) != 'ALL') $map[] = ['type','=',(int)$data['type']];
                }
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $field = '*';
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_inout_log')->where($map)->field($field)
                        ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '3', 'msg' => '当前页下无数据', 'count' => '0', 'data' => []]);
                }
                $res = ['code' => 0, 'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                foreach ($res['data'] as $key => &$val) {
                    $val['type_txt'] = _getDictNameTxt($val['type'],$crkType);
                    $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d',$val['create_time']) : '';
                    $val['except_time'] = $val['except_time'] > 0 ? date('Y-m-d',$val['except_time']) : '';
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
        $this->assign([
            'drugs_id' => $drugs_id,
            'drugs_name' => $drugs_name,
            'crk_type_list' => $crkType,  //出入库方式
        ]);
        return $this->view->fetch();
    }

}
